<template>
  <common-list>
    <common-search slot="search" @search="handleQuery" @reset="resetQuery">
      <el-form
        :model="queryParams"
        ref="queryForm"
        :inline="true"
        @submit.native.prevent
        v-show="showSearch"
        label-width="65px"
      >
        <el-form-item label="主机地址" prop="hostIp">
          <common-input
            v-model="queryParams.hostIp"
            @enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="主机端口" prop="hostPort">
          <common-input
            v-model="queryParams.hostPort"
            @enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="发送协议" prop="protocol">
          <el-select placeholder="请选择" v-model="queryParams.protocol">
            <el-option label="全部" :value="null"></el-option>
            <el-option label="TCP" value="TCP"></el-option>
            <el-option label="UDP" value="UDP"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </common-search>
    <!-- 中-->
    <div slot="tools">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            @click="handleAdd"
            v-hasPermi="['config:syslog:add']"
            >新增
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            :disabled="!showBatch"
            icon="el-icon-delete"
            @click="handleDelete"
            v-hasPermi="['config:syslog:remove']"
            >批量删除
          </el-button>
        </el-col>
      </el-row>
    </div>
    <common-table
      slot="content"
      :data="List"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主机地址" align="left" prop="hostIp" />
      <el-table-column label="主机端口" align="left" prop="hostPort" />
      <el-table-column label="发送协议" align="left" prop="protocol" />
      <el-table-column
        label="备注"
        align="left"
        prop="remark"
        show-overflow-tooltip
      />
      <el-table-column label="状态" align="center">
        <template slot-scope="scope">
          <el-tag type="success" v-if="scope.row.status === '0'">启用</el-tag>
          <el-tag type="danger" v-else-if="scope.row.status === '1'"
            >停用
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="left" width="125">
        <template slot-scope="scope">
          <!-- <el-button
            type="text"
            @click="viewDetail(scope.row)"
            >详情
          </el-button> -->
          <el-button
            type="text"
            @click="edit(scope.row)"
            v-hasPermi="['config:syslog:edit']"
            >编辑
          </el-button>
          <el-button
            type="text"
            @click="handleShake(scope.row)"
            v-hasPermi="['config:syslog:edit']"
            :disabled="scope.row.isDisabledForShake"
          >
            <!--   按钮状态 -->
            <span v-if="scope.row.status === '1'">启用</span>
            <span v-if="scope.row.status === '0'">停用</span>
          </el-button>
          <el-button
            type="text"
            @click="handleDelete(scope.row)"
            v-hasPermi="['config:syslog:remove']"
            >删除
          </el-button>
        </template>
      </el-table-column>
    </common-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 添加或修改syslog服务器配置对话框 -->
    <common-edit-dialog
      :title="isEdit ? '编辑日志服务' : '新增日志服务'"
      :visible.sync="open"
      :button-loading="loading"
      @cancel="cancel"
      @submit="submitForm"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px"  @submit.native.prevent>
        <el-row :gutter="18">
          <el-col :span="24">
            <el-form-item label="主机地址" prop="hostIp">
              <common-input v-model="form.hostIp" :verify="false" placeholder="支持IPV4/IPV6/URL格式" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="主机端口" prop="hostPort">
              <common-input-number
                :max-length="5"
                v-model="form.hostPort"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发送协议" prop="protocol">
              <el-select placeholder="请选择" v-model="form.protocol" filterable
                         clearable>
                <el-option label="TCP" value="TCP"></el-option>
                <el-option label="UDP" value="UDP"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <common-input
                v-model="form.remark"
                type="textarea"
                placeholder="请输入"
                show-overflow-tooltip
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </common-edit-dialog>
    <syslog-detail ref="syslogDetail"></syslog-detail>
  </common-list>
</template>

<script>
import {
  listConfig,
  getConfig,
  delConfig,
  addConfig,
  updateConfig,
} from "@/api/system/syslog";
import { portRule } from "@/utils/formRules";
import BaseList from "@/mixins/BaseList";
import SyslogDetail from "./components/syslogDetail"
import { validateIPAndURL } from "@/utils/formValidates"

export default {
  name: "Config",
  mixins: [BaseList],
  components: {
    SyslogDetail
  },
  data() {
    return {
      isEdit: false,
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // syslog服务器配置表格数据
      List: [],
      // 编辑/新增弹出层标题
      title: "",
      //
      sending: "",
      // 编辑新增弹框显示
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1, //页
        pageSize: 10, //一页中的数据条数
        hostIp: null,
        hostPort: null,
        protocol: null,
      },
      // 表单参数
      form: {
        id: null,
        hostIp: null,
        hostPort: 80,
        protocol: null,
        remark: null,
      },
      // 表单校验
      rules: {
        hostIp: [
          { required: true, message: '请输入主机地址', trigger: 'blur' },
          { required: true, message: '主机地址错误，支持IPV4/IPV6/URL格式', validator: validateIPAndURL, trigger: 'blur' }
        ],
        hostPort: portRule,
        protocol: [
          {
            required: true,
            message: "请选择发送协议",
            trigger: "blur",
          },
        ],
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    //  启用/停用
    changeStatus(row) {
      // row.status==='0'? row.status=1:row.status=0
      // row.status = row.status === '0' ? 1 : 0
      return new Promise((resolve, reject) => {
        let status = row.status === "0" ? "1" : "0";
        updateConfig({ status: status, id: row.id })
          .then((res) => {
            if (res && res.code === 200) {
              this.$GlobalSuccessMessage("操作成功");
              this.getList();
              resolve(res);
            } else {
              reject();
              this.$GlobalErrorConfirm("操作失败", res.msg).then();
            }
          }).catch(() => reject())
      });
    },
    /** 查询syslog服务器配置列表 */
    getList() {
      listConfig(this.queryParams)
        .then((res) => {
          if (res && res.code === 200) {
            this.List = res.rows.reduce((r, c) => {
              r.push({
                ...c,
                isDisabledForShake: false,
              });
              return r;
            }, []);
            this.total = res && res.total ? res.total : 0;
          } else {
            this.List = [];
            this.total = 0;
            this.handleListTips(res)
          }
        })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        hostIp: null,
        hostPort: 80,
        protocol: null,
        remark: null,
      };
      this.resetForm("form");
    },
    viewDetail(row){
      this.$refs.syslogDetail.show(row);
    },
    /** 编辑按钮操作 */
    edit(row) {
      this.isEdit = true;
      if (row.status === "0") {
        this.$GlobalErrorConfirm("编辑失败", "启用状态下不允许编辑");
      } else {
        this.open = true;
        Reflect.ownKeys(this.form).forEach((k) => (this.form[k] = row[k]));
        this.form.hostPort=Number(row.hostPort)
      }
    },
    /** 查询按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = this.$options.data().queryParams
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.open = true;
      this.isEdit = false;
      this.reset();
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.loading=true
          if (this.isEdit) {
            updateConfig(this.form)
              .then((res) => {
                if (res && res.code === 200) {
                  this.$GlobalSuccessMessage("编辑成功");
                  this.open=false
                  this.getList();
                } else {
                  this.$GlobalErrorConfirm("编辑失败", res.msg);
                }
              })
              .finally(() => {
                this.loading=false
              });
          } else {
            addConfig(this.form)
              .then((res) => {
                if (res && res.code === 200) {
                  this.$GlobalSuccessMessage("新增成功");
                  this.open = false;
                  this.getList();
                } else {
                  this.$GlobalErrorConfirm("新增失败", res.msg);
                }
              })
              .finally(()=>{
                this.loading=false
              })
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      if (row.status === "0") {
        this.$GlobalErrorConfirm("删除失败", "启用状态下不允许删除");
        return;
      }
      let status = this.List.find(
        (v) => this.ids.includes(v.id) && v.status === "0"
      );
      if (status) {
        this.$GlobalErrorConfirm("删除失败", "启用状态下不允许删除");
        return;
      }
      const ids = row?.id || this.ids.join(",");
      this.$GlobalDeleteConfirm().then(() => {
        delConfig({ ids })
          .then((res) => {
            if (res && res.code === 200) {
              this.$GlobalSuccessMessage("删除成功");
              if (this.queryParams.pageNum>1 && ids.split(',').length===this.List.length){
                this.queryParams.pageNum-=1
              }
              this.getList();
            } else {
              this.$GlobalErrorConfirm("删除失败", res.msg);
            }
          })
      }).catch(()=>{});
    },
  },
};
</script>
